package com.sjtuy.copycatinfo.ui.main;

import androidx.arch.core.util.Function;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Transformations;
import androidx.lifecycle.ViewModel;

public class PageViewModel extends ViewModel {

    private MutableLiveData<Integer> mIndex = new MutableLiveData<>();
    private LiveData<String> mText = Transformations.map(mIndex, new Function<Integer, String>() {
        @Override
        public String apply(Integer input) {
            if(input.equals(1)){
                return execCmdAndGetResult("cat /proc/cpuinfo")+"\n";
            }else if(input.equals(2)){
                return execCmdAndGetResult("cat /proc/meminfo")+"\n";
            }else if(input.equals(3)){
                return execCmdAndGetResult("df")+"\n";
            }else if(input.equals(4)){
                return execCmdAndGetResult("getprop")+"\n";
            }
            return "";
        }
    });

    public void setIndex(int index) {
        mIndex.setValue(index);
    }

    public LiveData<String> getText() {
        return mText;
    }

    private String execCmdAndGetResult(String cmd){
        try {
            Process cpu=Runtime.getRuntime().exec(cmd);
            int len;
            byte[] tmp = new byte[1024];
            StringBuilder sb = new StringBuilder();
            while ((len = cpu.getInputStream().read(tmp)) > 0) {
                sb.append(new String(tmp, 0, len));

            }
            return sb.toString();
        }catch (Exception e){
            return e.toString();
        }
    }
}